package org.richie144.ext4.ajax.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.richie144.ext4.ajax.dao.EmpDao;
import org.richie144.ext4.ajax.domain.Emp;
import org.richie144.ext4.ajax.util.DBConnection;

/**
 * 
 * 
 * 项目名称：ext4-panel-ajax
 * 类名称：EmpDaoImpl
 * 类描述：Emp Dao 实现
 * 创建人：任欢
 * 创建时间：2012-8-23 下午1:19:41
 * 修改人：任欢
 * 修改时间：2012-8-23 下午1:19:41
 * 修改备注：
 * @version 
 *
 */
public class EmpDaoImpl implements EmpDao{
	
	private static final Logger LOGGER = Logger.getLogger(EmpDaoImpl.class);
	
	private final static String GETALL ="SELECT * FROM emp";
	
	private final static String COUNT ="SELECT COUNT(empno) empcount FROM emp";
	@Override
	public List<Emp> getAll() {
		Emp emp = null;
		List<Emp> empList = null;
		Connection conn = null;
		PreparedStatement ptst = null;
		ResultSet rs = null;
		try {
			empList = new ArrayList<Emp>();
			conn = DBConnection.getConnection();
			ptst = conn.prepareStatement(GETALL);
			rs = ptst.executeQuery();
			while(rs.next()) {
				emp = new Emp(rs.getInt("empno"), rs.getString("ename"), rs.getString("job"), rs.getInt("mgr"),rs.getTimestamp("hiredate"), rs.getDouble("sal"), rs.getDouble("comm"), rs.getInt("deptno"));
				empList.add(emp);
				emp = null;
			}
			return empList;
		} catch (SQLException e) {
			LOGGER.debug("sql 语句"+GETALL+"有语法错误");
			e.printStackTrace();
		} finally {
			try {
				if(rs!=null) {
					rs.close();
					rs = null;
				}
				if(ptst!=null){
					ptst.close();
					ptst = null;
				}
				if(conn!=null){
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				LOGGER.debug("回收资源异常 !");
				e.printStackTrace();
			}
		}
		return empList;
	}
	@Override
	public long count() {
		long count = 0;
		Connection conn = null;
		PreparedStatement ptst = null;
		ResultSet rs = null;
		try {
			conn = DBConnection.getConnection();
			ptst = conn.prepareStatement(COUNT);
			rs = ptst.executeQuery();
			if(rs.next()) {
				count = rs.getLong("empcount");
			}
			return count;
		} catch (SQLException e) {
			LOGGER.debug("sql 语句"+GETALL+"有语法错误");
			e.printStackTrace();
		} finally {
			try {
				if(rs!=null) {
					rs.close();
					rs = null;
				}
				if(ptst!=null){
					ptst.close();
					ptst = null;
				}
				if(conn!=null){
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				LOGGER.debug("回收资源异常 !");
				e.printStackTrace();
			}
		}
		return count;
	}

}
